package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);

    }

    @Override
    public List<AddressBook> list() {
        List<AddressBook>addressBooks=addressBookMapper.selectByUserId(BaseContext.getCurrentId());
        return addressBooks;
    }

    @Override
    public AddressBook getDefault() {
        AddressBook addressBook=addressBookMapper.selectDefault(BaseContext.getCurrentId());
        return addressBook;
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    @Override
    public void delete(Long id) {
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.deleteById(id,userId);
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook=addressBookMapper.getById(id);
        return addressBook;
    }

    @Override
    public void update(Long id) {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBooks = addressBookMapper.selectByUserId(userId);
        for (AddressBook addressBook : addressBooks) {
            if ((long)addressBook.getId()==id) {
                addressBook.setIsDefault(1);
            } else {
                addressBook.setIsDefault(0);
            }
            addressBookMapper.update(addressBook);
        }
    }
}
